﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using blackhouse.Web;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
using blackhouse.WebNemo.Data;
using blackhouse.WebNemo.Data.Cache;
using System.Runtime.Caching;
using blackhouse.WebNemo.Business.Groups;

namespace blackhouse.WebNemo.Web {
    /// <summary>
    /// Summary description for NemoIdDynamicImage
    /// </summary>
    public class NemoIdDynamicImage : DynamicImage {

        #region Fields

        private string tableName = "";
        private string columnName = "";
        private int recordId = 0;
        private RecordFile file;
        private IDataAccess data;

        #endregion

        #region Properties

        public IDataAccess Data {
            get {
                if (this.data == null)
                    this.data = blackhouse.WebNemo.Business.Factory.Instance().GetDataAccess();
                return this.data;
            }
        }

        #endregion

        #region DynamicImage Members

        protected override string GetGuid(string fileName) {
            this.SetConfiguration();
            return this.file.FileGuid.ToString();
            //Dictionary<int, string> guids = this.Data.GetFileGuids(this.tableName, this.columnName);
            //if (guids.ContainsKey(this.recordId))
            //    return guids[this.recordId];
            //else
            //    return String.Empty;
        }

        protected override System.IO.Stream ReadImageStream(string fileNameWithExtension) {
            this.SetConfiguration();
            if (!this.file.Exist) return null;
            byte[] data = this.file.GetData();
            if (data != null) {
                MemoryStream mst = new MemoryStream();
                mst.Write(data, 0, data.Length);
                mst.Position = 0;
                return mst;
            }
            return null;
        }

        protected override System.Drawing.Imaging.ColorMatrix GetModification() {
            return null;
        }

        //protected override string GetFileExtension(Uri url) {
        //    this.SetConfiguration();
        //    return HttpContext.Current.Request["file"].ReplaceEx("?nocache=1", "").Split('.').Last();
        //}

        protected override string GetFileNameWithExtension(Uri url) {
            this.SetConfiguration();
            return HttpContext.Current.Request["file"].ReplaceEx("?nocache=1", "");
        }

        protected override bool GetBoxSizeFillInner(Uri url) {
            string fi = HttpContext.Current.Request["fillInner"];
            return !string.IsNullOrEmpty(fi) && fi == "1";
        }

        protected override System.Drawing.Size GetBoxSize(Uri url) {
            int width, height;
            if (
                Int32.TryParse(HttpContext.Current.Request["width"], out width)
                && Int32.TryParse(HttpContext.Current.Request["height"], out height))
                return new System.Drawing.Size(width, height);
            else
                return System.Drawing.Size.Empty;
        }

        protected override ImageWatermark[] GetWatermarks() {
            string cacheKey = "watermarks." + this.tableName + "." + this.columnName;

            ImageWatermark[] watermarksTab = null;
            if (MemoryCache.Default.Contains(cacheKey))
                watermarksTab = MemoryCache.Default.Get(cacheKey) as ImageWatermark[];
            if (watermarksTab != null) return watermarksTab;
            List<ImageWatermark> watermarks = new List<ImageWatermark>();
            DirectoryInfo d = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/Nemo/PhotoWatermarks"));
            if (d.Exists) {
                FileInfo[] f = d.GetFiles(this.tableName + "." + this.columnName + ".*");
                foreach (FileInfo file in f) {
                    ImageWatermark watermark = this.GetFileBasedWatermark(file);
                    if (watermark != null)
                        watermarks.Add(watermark);
                }
            }
            watermarksTab = watermarks.ToArray();
            FileInfo fiCache = new FileInfo(HttpContext.Current.Server.MapPath("~/Nemo/PhotoWatermarks/watermarks.cache"));
            if (fiCache.Exists) {
                List<string> fileMonit = new List<string>(1);
                fileMonit.Add(fiCache.FullName);
                HostFileChangeMonitor changeMonitor = new HostFileChangeMonitor(fileMonit);
                CacheItem ci = new CacheItem(cacheKey, watermarksTab);
                CacheItemPolicy cp = new CacheItemPolicy();
                cp.SlidingExpiration = TimeSpan.FromMinutes(20);
                cp.ChangeMonitors.Add(changeMonitor);
                MemoryCache.Default.Add(ci, cp);
            }
            return watermarksTab;
        }

        protected ImageWatermark GetFileBasedWatermark(FileInfo file) {
            string[] fileParts = file.Name.Split('.');
            float percentWidth, percentHeight, percentPositionX, percentPositionY;
            if (this.ParsePercentBox(fileParts[2], out percentWidth, out percentHeight)
                && this.ParsePercentBox(fileParts[3], out percentPositionX, out percentPositionY)) {
                ImageWatermark watermark = new PhotoWatermark(file, percentWidth, percentHeight, percentPositionX, percentPositionY);
                return watermark;
            }
            else
                return null;
        }

        private bool ParsePercentBox(string textValue, out float w, out float h) {
            w = 0;
            h = 0;
            string[] tParts = textValue.Split('x');
            if (tParts.Length != 2) return false;
            return
                Single.TryParse(tParts[0], out w)
                && Single.TryParse(tParts[1], out h);
        }

        #endregion

        #region Methods

        private string GetConnectionString() {
            return ConfigurationManager.AppSettings["MSSQLConnectionString"];
        }

        private void SetConfiguration() {
            if (string.IsNullOrEmpty(this.tableName)) {
                this.columnName = HttpContext.Current.Request["column"];
                this.tableName = HttpContext.Current.Request["table"];
                if (Int32.TryParse(HttpContext.Current.Request["recordId"], out this.recordId)) {
                    this.file = new RecordFile(new GroupRecord(this.tableName, this.recordId), this.columnName);
                }
            }
        }

        #endregion

    }
}